package com.dingwen.auause.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dingwen.auause.entity.PermissionEntity;
import com.dingwen.auause.entity.UserEntity;
import com.dingwen.auause.service.PermissionService;
import com.dingwen.auause.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义用户认证授权
 *
 * @author dingwen
 * 2021.05.12 16:36
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;
    private final PermissionService permissionService;

    @Autowired
   public UserDetailsServiceImpl(UserService userService, PermissionService permissionService) {
        this.userService = userService;
        this.permissionService = permissionService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询用户信息
        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("username", username));

        List<GrantedAuthority> authorityList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(user)) { //如果用户不为空进行授权
            // 获取用户权限
            List<PermissionEntity> permissionEntityList = permissionService.getPermissionsByUserId(user.getId());

            // 声明用户授权
            permissionEntityList.stream().parallel().forEach(permissionEntity -> {
                if (!ObjectUtils.isEmpty(permissionEntity) && StringUtils.hasText(permissionEntity.getEnname())) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permissionEntity.getEnname());
                    authorityList.add(grantedAuthority);
                }
            });
        }
        // 完成授权工作
        return new User(user.getUsername(), user.getPassword(), authorityList);
    }
}
